package com.example.register.service;

import com.example.register.EventType;
import com.example.registerapi.RegisterInfo;
import com.example.registerapi.RegisterInfoHolder;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Set;

@Service
public class ServerService implements BeanFactoryAware {

    @Autowired
    private RestTemplate restTemplate;

    private BeanFactory beanFactory;



    @Async
    public void doPublishRegister(String name,String port,String ip){
        Set<RegisterInfo> listeners = RegisterInfoHolder.getListeners();
        for (RegisterInfo listener : listeners) {
            if (!listener.isOnline()){
                continue;
            }
            String url = String.format("%s?name=%s&port=%s&ip=%s", listener.getHost()+ "/serverOnline", name, port, ip);
            try {
                restTemplate.getForObject(url, String.class);
            }catch (Exception e){
                listener.setOnline(false);
                System.out.println("服务上线通知失败："+e.getMessage());
            }

        }
    }

    @Async
    public void doPublishOffline(String name,String port,String ip){
        Set<RegisterInfo> listeners = RegisterInfoHolder.getListeners();
        for (RegisterInfo listener : listeners) {
            if (!listener.isOnline()){
                continue;
            }
            String url = String.format("%s?name=%s&port=%s&ip=%s", listener.getHost()+ "/serverOffline", name, port, ip);
            try {
                restTemplate.getForObject(url, String.class);
            }catch (Exception e){
                listener.setOnline(false);
                System.out.println("服务下线通知失败："+e.getMessage());
            }

        }
    }

    public void publishEvent(String name, String port, String ip, EventType eventType) {
        switch (eventType){
            case REGISTER:
                beanFactory.getBean(ServerService.class).doPublishRegister(name,port,ip);
                break;
            case OFFLINE:
                beanFactory.getBean(ServerService.class).doPublishOffline(name,port,ip);
                break;
            default:

        }

    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    public void publishEvent(RegisterInfo listener, EventType eventType) {
        this.publishEvent(listener.getName(),listener.getPort() + "",listener.getIp(),eventType);
    }
}
